//
//  ZWComposeView.swift
//  ZWWeibo
//
//  Created by flyiron on 16/4/25.
//  Copyright © 2016年 flyiron. All rights reserved.
//

import UIKit
import pop

class ZWComposeView: UIView {
    
    lazy var buttonInfoList:[ZWComposeMenuItemInfo] = {
        var tempArr = [ZWComposeMenuItemInfo]()
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        let array = NSArray(contentsOfFile: path!)
        for value in array! {
            let info = ZWComposeMenuItemInfo(dict: value as! [String : AnyObject])
            tempArr.append(info)
        }
        return tempArr
    }()
    
    var buttonArr:[ZWMenuButton] = []
    var target:UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
//        backgroundColor = UIColor.redColor()
        frame = UIScreen.mainScreen().bounds
        let backgroundImage = UIImageView(image: getScreenShot().applyLightEffect())
        addSubview(backgroundImage)
        addSubview(sloganImage)
        
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        
        addMenuBTN()
    }
    deinit{
        print("要死要死")
    }
    
    func show(target:UIViewController){  
        self.target = target
        target.view.addSubview(self)
    }
    
    @objc private func clickMenuBTN(button:UIButton){
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.buttonArr {
                
                value.alpha = 0.01
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.01, 0.01)
                }
            }
            })
        
//        let vc = ZWComposeViewController()
        let model = buttonInfoList[button.tag]
        let type = NSClassFromString(model.className!) as! UIViewController.Type
        let vc = type.init()
        
        target?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
            self.removeFromSuperview()
        })
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (i,value) in buttonArr.reverse().enumerate() {
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            anim.toValue = NSValue(CGPoint: CGPointMake(value.center.x, value.center.y + 350))
            anim.springSpeed = 10
            anim.springBounciness = 8
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(i) * 0.025 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                value.pop_addAnimation(anim, forKey: nil)
            })
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
    }
    //动画
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        for (i,value) in buttonArr.enumerate() {
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            anim.toValue = NSValue(CGPoint: CGPointMake(value.center.x, value.center.y - 350))
            anim.springSpeed = 10
            anim.springBounciness = 8
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(i) * 0.025 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                value.pop_addAnimation(anim, forKey: nil)
            })
        }
    }
    //添加菜单按钮
    private func addMenuBTN(){
        let buttonW:CGFloat = 80
        let buttonH:CGFloat = 110
        let margin = (SCREENW - 3 * buttonW)/4
        for (i,value) in buttonInfoList.enumerate() {
            let row = i / 3
            let col = i % 3
            let button = ZWMenuButton(textColor: UIColor.lightGrayColor(), fontSize: 14)
            button.addTarget(self, action: #selector(ZWComposeView.clickMenuBTN(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = i
            button.setTitle(value.title, forState: UIControlState.Normal)
            button.setImage(UIImage(named: value.icon!), forState: UIControlState.Normal)
            button.frame = CGRectMake(margin * CGFloat(col + 1) + buttonW * CGFloat(col) , buttonH * CGFloat(row) + SCREENH, buttonW, buttonH)
            buttonArr.append(button)
            addSubview(button)
        }
            }
    //获取屏幕截图
    private func getScreenShot() -> UIImage {
        let window = UIApplication.sharedApplication().keyWindow
        let rect = window!.frame
        //开启图形上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        //将屏幕内容渲染到上下文中
        window?.drawViewHierarchyInRect(rect, afterScreenUpdates: true)
        //获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭图形上下文
        UIGraphicsEndImageContext()
        //返回图片
        return image
    }
    // MARK: - 懒加载控件
    private lazy var sloganImage = UIImageView(image: UIImage(named: "compose_slogan"))
    
    
}
